#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
仪表盘页面模块
"""

import logging
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel,
    QFrame, QGridLayout, QSizePolicy, QSpacerItem
)
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QFont, QColor


class StatCard(QFrame):
    """统计卡片组件"""
    
    def __init__(self, title, value, icon=None, color="#3498db"):
        super().__init__()
        self.setFrameShape(QFrame.Shape.StyledPanel)
        self.setStyleSheet(f"background-color: {color}; color: white; border-radius: 8px;")
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        
        # 创建布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 标题
        title_label = QLabel(title)
        title_label.setStyleSheet("font-size: 14px; font-weight: bold;")
        layout.addWidget(title_label)
        
        # 值
        value_label = QLabel(str(value))
        value_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        value_label.setAlignment(Qt.AlignmentFlag.AlignRight)
        layout.addWidget(value_label)
        
        self.value_label = value_label
    
    def update_value(self, value):
        """更新卡片值"""
        self.value_label.setText(str(value))


class DashboardPage(QWidget):
    """仪表盘页面"""
    
    def __init__(self, config, database, task_scheduler):
        super().__init__()
        self.config = config
        self.database = database
        self.task_scheduler = task_scheduler
        self._setup_ui()
        
        # 设置定时器更新统计信息
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self._update_stats)
        self.update_timer.start(5000)  # 5秒更新一次
        
        # 初始化统计数据
        self._update_stats()
        
        logging.info("仪表盘页面已初始化")
    
    def _setup_ui(self):
        """设置UI"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)
        
        # 标题
        title_label = QLabel("系统仪表盘")
        title_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        main_layout.addWidget(title_label)
        
        # 统计卡片区域
        stats_layout = QGridLayout()
        stats_layout.setSpacing(15)
        
        # 任务统计卡片
        self.total_tasks_card = StatCard("总任务数", "0", color="#3498db")
        stats_layout.addWidget(self.total_tasks_card, 0, 0)
        
        self.running_tasks_card = StatCard("运行中任务", "0", color="#2ecc71")
        stats_layout.addWidget(self.running_tasks_card, 0, 1)
        
        self.pending_tasks_card = StatCard("等待中任务", "0", color="#f39c12")
        stats_layout.addWidget(self.pending_tasks_card, 0, 2)
        
        self.failed_tasks_card = StatCard("失败任务", "0", color="#e74c3c")
        stats_layout.addWidget(self.failed_tasks_card, 0, 3)
        
        # 触发器统计卡片
        self.file_triggers_card = StatCard("文件触发器", "0", color="#9b59b6")
        stats_layout.addWidget(self.file_triggers_card, 1, 0)
        
        self.webhook_triggers_card = StatCard("Webhook触发器", "0", color="#1abc9c")
        stats_layout.addWidget(self.webhook_triggers_card, 1, 1)
        
        self.email_triggers_card = StatCard("邮件触发器", "0", color="#34495e")
        stats_layout.addWidget(self.email_triggers_card, 1, 2)
        
        self.schedule_triggers_card = StatCard("定时触发器", "0", color="#16a085")
        stats_layout.addWidget(self.schedule_triggers_card, 1, 3)
        
        main_layout.addLayout(stats_layout)
        
        # 系统状态区域
        status_frame = QFrame()
        status_frame.setFrameShape(QFrame.Shape.StyledPanel)
        status_frame.setStyleSheet("background-color: #f8f9fa; border-radius: 8px;")
        status_layout = QVBoxLayout(status_frame)
        
        status_title = QLabel("系统状态")
        status_title.setStyleSheet("font-size: 18px; font-weight: bold;")
        status_layout.addWidget(status_title)
        
        # 系统状态信息
        self.system_status_label = QLabel("系统运行正常")
        self.system_status_label.setStyleSheet("color: #2ecc71; font-weight: bold;")
        status_layout.addWidget(self.system_status_label)
        
        # 集群状态信息
        cluster_status_layout = QHBoxLayout()
        cluster_status_layout.addWidget(QLabel("集群状态:"))
        self.cluster_status_label = QLabel("未启用")
        self.cluster_status_label.setStyleSheet("color: #7f8c8d;")
        cluster_status_layout.addWidget(self.cluster_status_label)
        cluster_status_layout.addStretch()
        status_layout.addLayout(cluster_status_layout)
        
        # 队列状态信息
        queue_status_layout = QHBoxLayout()
        queue_status_layout.addWidget(QLabel("队列状态:"))
        self.queue_status_label = QLabel("正常")
        self.queue_status_label.setStyleSheet("color: #2ecc71;")
        queue_status_layout.addWidget(self.queue_status_label)
        queue_status_layout.addStretch()
        status_layout.addLayout(queue_status_layout)
        
        main_layout.addWidget(status_frame)
        
        # 添加弹性空间
        main_layout.addStretch()
    
    def _update_stats(self):
        """更新统计数据"""
        # 从各个页面获取实际数据
        main_window = self.window()
        
        # 更新任务统计
        if hasattr(main_window, "tasks_page"):
            tasks = main_window.tasks_page.tasks
            total_tasks = len(tasks)
            running_tasks = sum(1 for task in tasks if task["status"] == "运行中")
            pending_tasks = sum(1 for task in tasks if task["status"] == "等待中")
            failed_tasks = sum(1 for task in tasks if task["status"] == "失败")
            
            self.total_tasks_card.update_value(total_tasks)
            self.running_tasks_card.update_value(running_tasks)
            self.pending_tasks_card.update_value(pending_tasks)
            self.failed_tasks_card.update_value(failed_tasks)
        else:
            # 使用默认值
            self.total_tasks_card.update_value(10)
            self.running_tasks_card.update_value(2)
            self.pending_tasks_card.update_value(5)
            self.failed_tasks_card.update_value(1)
        
        # 更新触发器统计
        if hasattr(main_window, "triggers_page"):
            triggers = main_window.triggers_page.triggers
            file_triggers = sum(1 for t in triggers if t["type"] == "file")
            webhook_triggers = sum(1 for t in triggers if t["type"] == "webhook")
            email_triggers = sum(1 for t in triggers if t["type"] == "email")
            schedule_triggers = sum(1 for t in triggers if t["type"] == "schedule")
            
            self.file_triggers_card.update_value(file_triggers)
            self.webhook_triggers_card.update_value(webhook_triggers)
            self.email_triggers_card.update_value(email_triggers)
            self.schedule_triggers_card.update_value(schedule_triggers)
        else:
            # 使用默认值
            self.file_triggers_card.update_value(3)
            self.webhook_triggers_card.update_value(2)
            self.email_triggers_card.update_value(1)
            self.schedule_triggers_card.update_value(4)
        
        # 更新系统状态
        # 这里可以添加实际的系统状态检查逻辑
        
        # 更新集群状态
        if self.config.get("cluster", {}).get("enabled", False):
            self.cluster_status_label.setText("正常运行")
            self.cluster_status_label.setStyleSheet("color: #2ecc71;")
        else:
            self.cluster_status_label.setText("未启用")
            self.cluster_status_label.setStyleSheet("color: #7f8c8d;")
            
        # 更新队列状态
        if hasattr(main_window, "queue_page"):
            queues = main_window.queue_page.queues
            if any(q["status"] == "运行中" for q in queues):
                self.queue_status_label.setText("正常")
                self.queue_status_label.setStyleSheet("color: #2ecc71;")
            else:
                self.queue_status_label.setText("暂停")
                self.queue_status_label.setStyleSheet("color: #e74c3c;")